<template>
  <el-dialog
    :close-on-click-modal="false"
    :before-close="dialogCancel"
    :visible.sync="isVisible"
    :title="title"
    width="860px"
    @opened="initCollapse"
  >
    <el-collapse v-model="activeNames">
      <el-collapse-item title="历史填报" name="1">
        <el-collapse v-model="historyDetailActiveNames" accordion>
          <el-collapse-item v-for="(item,index) in progressList" :key="index" :name="index">
            <template slot="title">
              <span>
                <div
                  class="historyCollapse"
                >{{ parseTime(item.startTime,'{y}-{m}-{d}') }} 至 {{ parseTime(item.endTime,'{y}-{m}-{d}') }}</div>
                <div v-if="item.timeUse != null & item.timeUse != 0 " class="historyCollapse">消耗{{ item.timeUse }}（人/天）</div>
                <div v-if="item.progress != null & item.progress != 0" class="historyCollapse">进度{{ numFilter(item.progress*100, 0) }}%</div>
                <div class="collapseIcon">
                  <i class="el-icon-edit-outline" @click.stop="editOldProgress(item,index)" />
                </div>
              </span>
            </template>
            <div class="historyCollapseDetail">{{ item.describe }}</div>
          </el-collapse-item>
        </el-collapse>
      </el-collapse-item>
      <el-collapse-item title="进度填报" name="2">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px" inline>
          <el-form-item label="此周期时间" prop="timeArea">
            <el-date-picker
              v-model="form.timeArea"
              :default-time="['00:00:00','23:59:59']"
              type="daterange"
              range-separator=":"
              size="small"
              class="date-item"
              value-format="yyyy-MM-dd"
              start-placeholder="起始时间"
              end-placeholder="结束时间"
              @change="updateTimeArea"
            />
          </el-form-item>
          <el-form-item v-if="false" label="填报时间">
            <el-input v-model="form.updateTime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="项目进度" prop="progress">
            <el-input v-model.number="form.progress" type="number" style="width: 100px;" />%
          </el-form-item>
          <el-form-item label="项目耗时" prop="timeUse">
            <el-input v-model="form.timeUse" style="width: 80px;" />（人/天）
          </el-form-item>
          <el-form-item label="具体描述" prop="describe">
            <el-tooltip :disabled="isUpdate" class="item" effect="dark" placement="top">
              <div slot="content">
                <span>
                  {{ suggestWord }}
                </span>
                <div v-for="(item,index) in workDescList" :key="index" :name="index">
                  {{ item.describe }}
                </div>
              </div>
              <el-input v-model="form.describe" :rows="5" type="textarea" style="width: 645px;" />
            </el-tooltip>
          </el-form-item>
          <el-form-item v-if="false" label="项目ID" prop="projectId">
            <el-input v-model="form.projectId" style="width: 370px;" />
          </el-form-item>
          <el-form-item v-if="false" label="项目阶段ID" prop="stageId">
            <el-input v-model="form.stageId" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div>
          <el-button class="stageprogressdialogfoot" :loading="crud.cu === 2" type="primary" @click="taskAssignSubmit(form)">
            <template v-if="isUpdate">更新历史填报</template>
            <template v-if="!isUpdate">确认</template>
          </el-button>
          <el-button class="stageprogressdialogfoot" type="warning" @click="reSetMode">清空</el-button>

          <el-button class="stageprogressdialogfoot" type="text" @click="dialogCancel">取消</el-button>
        </div>
      </el-collapse-item>
    </el-collapse>
  </el-dialog>
</template>>
<script>
import CRUD from '@crud/crud'
import { parseTime } from '@/utils/index'
import Vue from 'vue'
import { get as getProjectStageTaskList } from '@/api/projectAllTaskView'
import { get as getProjectStageProgress, edit as editProjectStageProgress, add as addProjectStageProgress } from '@/api/projectStageProgress'
export default {
  name: 'ProjectStageProgressDialog',
  props: {
    isVisible: {
      type: Boolean,
      default: false
    },
    crud: {
      type: Object,
      default: null
    }
  },
  data() {
    var numberValidate = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('项目进度不能为空'))
      } else {
        if (value < 0) {
          callback(new Error('进度须在0%~100%之间'))
        } else if (value > 100) {
          callback(new Error('进度须在0%~100%之间'))
        }
        callback()
      }
    }
    return {
      title: '任务阶段进度填报',
      rules: {
        timeArea: [
          { required: true, message: '时间不能为空', trigger: 'blur' }
        ],
        progress: [
          { required: true, message: '进度不能为空', trigger: 'blur' },
          { type: 'number', message: '进度必须为数字' },
          { validator: numberValidate, trigger: 'blur' }
        ],
        describe: [
          { required: true, message: '周报描述不能为空', trigger: 'blur' }
        ]
      },
      form: {
      },
      suggestWord: '',
      workDescList: [],
      oldWorkLInfo: {},
      isUpdate: false,
      activeNames: ['2'],
      historyDetailActiveNames: [],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      progressList: [],
      showHistoryProgress: {},
      defaultForm: { currentStageID: 0, currentProjectID: 0 }
    }
  },
  methods: {
    parseTime,
    reSetMode() {
      this.form = {}
      this.isUpdate = false
    },
    updateTimeArea() {
      // console.log('updateTime')
      if (this.form.timeArea != null && this.form.timeArea.length === 2) {
        this.form.startTime = new Date(this.form.timeArea[0]).getTime()
        this.form.endTime = new Date(this.form.timeArea[1]).getTime()
      }
    },
    updateColList() {
      // 更新历史填报的清单
      const searchInfo = { stageId: this.defaultForm.currentStageID }
      setTimeout(() => {
        getProjectStageProgress(searchInfo).then(res => { this.progressList = res.content })
      }, '2000')
    },
    numFilter(value, number) {
      const realVal = parseFloat(value).toFixed(number)
      return realVal
    },
    editOldProgress(item, index) {
      // console.log('editOldProgress')
      for (const key in item) {
        Vue.set(this.form, key, item[key])
      }
      if (this.form.progress != null) {
        this.form.progress = this.numFilter(this.form.progress * 100, 2) * 1.0
      }
      this.isUpdate = true
      this.form.timeArea = []
      this.form.timeArea.push(parseTime(this.form.startTime, '{y}-{m}-{d}'))
      this.form.timeArea.push(parseTime(this.form.endTime, '{y}-{m}-{d}'))
    },
    reSetDefault() {
      this.activeNames = ['2']
      this.historyDetailActiveNames = []
      this.progressList = []
    },
    initCollapse() {
      // console.log('initCollapse')
      console.log(this.crud.data)
      this.defaultForm.currentStageID = this.crud.form.id
      this.defaultForm.currentProjectID = this.crud.form.projectBase.id
      this.progressList = this.crud.form.progressList
      this.showHistoryProgress = this.progressList[this.progressList.length]
      this.generateProgressSuggest()
    },
    generateProgressSuggest() {
      // 生成填报建议
      const searchInfo = { stageId: this.defaultForm.currentStageID }
      this.workDescList = []
      this.suggestWord = ''
      getProjectStageTaskList(searchInfo).then(res => {
        this.oldWorkLInfo = res
        var issueNumber = 0
        var taskNumber = 0
        for (let i = 0; i < res.totalElements; i++) {
          if (res.content[i].id.substr(0, 1) === 't') {
            taskNumber = taskNumber + 1
          } else if (res.content[i].id.substr(0, 1) === 'i') {
            issueNumber = issueNumber + 1
          }
        }
        this.suggestWord = '此阶段当前有研发任务' + taskNumber + '项,问题' + issueNumber + '项，详情如下:'
        for (let i = 0; i < res.totalElements; i++) {
          this.workDescList.push({ describe: res.content[i].simpleDescribe + ',' + '已分配' + res.content[i].workerNo + '人' })
        }
      })
    },
    doInsertProgress() {
      addProjectStageProgress(this.form).then(res => {
        this.crud.notify('修改成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    },
    doUpdateProgess() {
      // console.log('doUpdateProgess')
      editProjectStageProgress(this.form).then(res => {
        this.crud.notify('填报成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    },
    taskAssignSubmit(data) {
      // console.log('try submit')
      // console.log(this.form)
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.stageId = this.defaultForm.currentStageID
          this.form.projectId = this.defaultForm.currentProjectID
          this.form.updateTime = new Date().getTime()
          if (this.form.id != null && this.form.id > 0) {
            if (this.form.progress != null) {
              this.form.progress = this.form.progress / 100
            }
            this.doUpdateProgess()
          } else {
            if (this.form.progress != null) {
              this.form.progress = this.form.progress / 100
            }
            this.doInsertProgress()
          }
          this.crud.refresh()
          this.reSetMode()
          this.updateColList()
        } else {
          console.log('valid error')
          return false
        }
      })
    },
    dialogCancel() {
      this.reSetMode()
      this.reSetDefault()
      this.$emit('dialogCancel', false)
    }
  }
}
</script>

<style scoped>
.stageprogressdialogfoot {
  float: right;
  margin-left: 2px;
}
.historyCollapse {
  display: inline;
  padding-left: 10px;
}
.historyCollapseDetail {
  padding-left: 30px;
}
.collapseIcon {
  display: inline;
  align-items: flex-end;
}
</style>
